// packageA/pages/makeup/makeup.js
Page({
  data: {
    selectedDate: '',
    selectedTime: '',
    typeId: 1, // 1:正常, 2:异常
    duration: 5, // 默认5分钟
    note: ''
  },

  onLoad(options) {
    // 获取传入的日期，如果没有则使用今天
    const date = options.date || this.formatDate(new Date());
    const time = this.formatTime(new Date());
    
    this.setData({
      selectedDate: date,
      selectedTime: time
    });
  },

  // 选择日期
  onDateChange(e) {
    this.setData({
      selectedDate: e.detail.value
    });
  },

  // 选择时间
  onTimeChange(e) {
    this.setData({
      selectedTime: e.detail.value
    });
  },

  // 选择类型
  onTypeChange(e) {
    this.setData({
      typeId: parseInt(e.detail.value) + 1
    });
  },

  // 直接选择类型
  selectType(e) {
    const type = parseInt(e.currentTarget.dataset.type);
    this.setData({
      typeId: type
    });
  },

  // 时长输入
  onDurationInput(e) {
    let value = e.detail.value;
    
    // 只允许数字输入，限制为两位数
    value = value.replace(/[^\d]/g, '');
    if (value.length > 2) {
      value = value.slice(0, 2);
    }
    
    this.setData({
      duration: value
    });
  },

  // 备注输入
  onNoteInput(e) {
    this.setData({
      note: e.detail.value
    });
  },

  // 保存补卡记录
  saveRecord() {
    const { selectedDate, selectedTime, typeId, duration, note } = this.data;
    
    if (!selectedDate || !selectedTime) {
      this.selectComponent('#customToast').showToast('请选择日期和时间');
      return;
    }
    
    // 检查时长是否有效
    if (!duration || duration === '' || parseInt(duration) === 0) {
      this.selectComponent('#customToast').showToast('请输入时长(1-99分钟)');
      return;
    }
    
    // 检查异常类型是否输入了备注
    if (typeId === 2 && (!note || note.trim() === '')) {
      this.selectComponent('#customToast').showToast('异常情况请输入备注信息');
      return;
    }

    // 检查是否已有相同时间的记录
    const records = wx.getStorageSync('poopRecords') || [];
    const existingRecord = records.find(record => 
      record.date === selectedDate && record.time === selectedTime
    );
    
    if (existingRecord) {
      wx.showModal({
        title: '提示',
        content: `该时间点(${selectedTime})已有记录，是否覆盖？`,
        success: (res) => {
          if (res.confirm) {
            this.doSaveRecord();
          }
        }
      });
    } else {
      this.doSaveRecord();
    }
  },

  // 执行保存
  doSaveRecord() {
    const { selectedDate, selectedTime, typeId, duration, note } = this.data;
    
    const record = {
      id: Date.now().toString(),
      date: selectedDate,
      time: selectedTime,
      typeId: typeId,
      duration: duration,
      durationSeconds: 0, // 补卡记录不记录秒数
      note: note,
      isManual: true // 标记为手动补卡
    };

    // 获取现有记录
    let records = wx.getStorageSync('poopRecords') || [];
    
    // 只删除相同日期和时间的记录（如果存在）
    records = records.filter(r => !(r.date === selectedDate && r.time === selectedTime));
    
    // 添加新记录
    records.push(record);
    
    // 按日期时间排序
    records.sort((a, b) => new Date(b.date + ' ' + b.time) - new Date(a.date + ' ' + a.time));
    
    // 保存到本地存储
    wx.setStorageSync('poopRecords', records);
    
    this.selectComponent('#customToast').showToast('补卡成功');
    
    // 延迟返回上一页
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 格式化时间
  formatTime(date) {
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${hours}:${minutes}`;
  }
});